﻿using System;
using System.IO;

namespace MangosRestarter
{
    /// <summary>
    /// 日志记录类
    /// </summary>
    internal static class Logger
    {
        private static readonly string LogFile =
            Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "MangosRestarter.log");

        private static readonly long MaxLogSize = 10 * 1024 * 1024; // 10MB
        private static readonly object _lock = new object();

        /// <summary>
        /// 写入日志
        /// </summary>
        internal static void Write(string text)
        {
            lock (_lock)
            {
                try
                {
                    // 检查日志文件大小，超过则轮转
                    if (File.Exists(LogFile) && new FileInfo(LogFile).Length > MaxLogSize)
                    {
                        string backupPath = $"{LogFile}.{DateTime.Now:yyyyMMddHHmmss}.bak";
                        File.Move(LogFile, backupPath);
                    }

                    File.AppendAllText(LogFile,
                        $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {text}{Environment.NewLine}",
                        System.Text.Encoding.UTF8);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"[Logger Error] {ex.Message}");
                }
            }
        }

        /// <summary>
        /// 清理旧日志
        /// </summary>
        internal static void CleanOldLogs(int keepDays = 30)
        {
            lock (_lock)
            {
                try
                {
                    var logDir = Path.GetDirectoryName(LogFile);
                    var pattern = "MangosRestarter.log*.bak";

                    foreach (var file in Directory.GetFiles(logDir, pattern))
                    {
                        var fileInfo = new FileInfo(file);
                        if (fileInfo.CreationTime < DateTime.Now.AddDays(-keepDays))
                        {
                            fileInfo.Delete();
                        }
                    }
                }
                catch (Exception ex)
                {
                    Write($"清理旧日志失败: {ex.Message}");
                }
            }
        }
    }
}